<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button class="get">get</button>
    <button class="post">post</button>
</body>
<script type="module">
    import {AjaxPromise} from "../js/ajax.js";
    var getBtn = document.getElementsByClassName("get")[0];
    var postBtn = document.getElementsByClassName("post")[0];

    getBtn.onclick = function(){
        AjaxPromise({
            type:"get",
            url:"/api/get",
            data:{
                name:"张三",
                age:18,
            },
            dataType:"json",
        }).then(res=>{
            console.log("请求成功",res);
        }).catch(err=>{
            throw err;
        })
    }

    postBtn.onclick = function () {

        // FormData
        // AjaxPromise({
        //     type:"post",
        //     url:"/api/post",
        //     data:{
        //         name:"张三",
        //         class:"2302",
        //     },
        //     dataType:"json",
        // }).then(res=>{
        //     console.log("请求成功",res);
        // }).catch(err=>{
        //     throw err;
        // })

        
        var  xhr = new XMLHttpRequest();
        xhr.open("post","/api/post",true);

        // FormData
        // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        // xhr.send(`name=张三&class=2302`);

        // json
        xhr.setRequestHeader("Content-Type","application/json");
        
        var data = {name:"张三",class:"2302"};
        xhr.send(JSON.stringify(data));

        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4&& xhr.status == 200){
                var res = xhr.responseText;
                res = JSON.parse(res);
                console.log(res);
            }
        }

    }
</script>
</html>